<template>
  <div class="task-container">
    <!-- 主要内容区域 - 合并搜索和列表 -->
    <el-card class="form-card task-list-card" shadow="hover">
      <template #header>
        <!-- 搜索区域 -->
        <div class="search-container">
          <div class="search-row">
            <div class="search-item">
              <span class="label">需求状态</span>
              <el-select
                v-model="status"
                placeholder="全部"
                class="input-width"
              >
                <el-option label="全部" value=""></el-option>
                <el-option label="已分配" value="已分配"></el-option>
                <el-option label="已推送" value="已推送"></el-option>
              </el-select>
            </div>
            <div class="search-item">
              <span class="label">需求名称</span>
              <el-input
                v-model="name"
                placeholder="请输入需求名称"
                class="input-width"
              ></el-input>
            </div>
            <div class="search-item">
              <span class="label">需求编号</span>
              <el-input
                v-model="code"
                placeholder="请输入需求编号"
                class="input-width"
              ></el-input>
            </div>
            <div class="buttons">
              <el-button type="primary" @click="handleSearch" :icon="Search"
                >查询</el-button
              >
              <el-button @click="resetSearch" :icon="RefreshRight"
                >重置</el-button
              >
            </div>
          </div>
        </div>
      </template>

      <div class="card-header">
        <div class="left-actions">
          <el-button
            type="primary"
            @click="openUploadDialog"
            class="add-task-btn"
            :icon="Plus"
          >
            创建任务
          </el-button>
        </div>
        <div class="right-actions">
          <el-button class="action-btn" :icon="Download"> 导出Excel </el-button>
          <el-button
            :disabled="multipleSelection.length === 0"
            @click="handleBatchAction"
            class="action-btn"
            :icon="Connection"
          >
            推送禅道
          </el-button>
        </div>
      </div>

      <!-- 表格区域 -->
      <el-table
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
        class="task-table"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="expand">
          <template #default="props">
            <TaskDetail :task="props.row" />
          </template>
        </el-table-column>
        <el-table-column
          prop="code"
          label="需求编号"
          width="150"
        ></el-table-column>
        <el-table-column prop="name" label="需求名称"></el-table-column>
        <el-table-column
          prop="status"
          label="需求状态"
          width="120"
        ></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleEdit(scope.row)"
            >
              管理
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 使用封装的任务上传组件 -->
    <TaskUpload
      v-model:visible="uploadDialogVisible"
      title="上传需求书"
      :allowedTypes="['doc', 'docx']"
      @upload-success="handleUploadSuccess"
      @upload-cancel="handleUploadCancel"
      :loading="uploadLoading"
    />

    <!-- AI处理响应区域 -->
    <el-card v-if="showResponse" class="form-card response-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>AI分析结果</span>
          <el-button type="text" @click="clearResponse">关闭</el-button>
        </div>
      </template>
      <div class="response-content">
        <el-skeleton :rows="6" animated v-if="aiLoading" />
        <div v-else>{{ aiResponse }}</div>
      </div>
    </el-card>

    <!-- 使用封装的任务编辑组件 -->
    <TaskEditDialog
      v-model="editDialogVisible"
      :task-data="editForm"
      @save="saveEdit"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import {
  Edit,
  Delete,
  Plus,
  FolderAdd,
  Search,
  RefreshRight,
  Download,
  Connection,
} from "@element-plus/icons-vue";
import { ElMessage, ElLoading } from "element-plus";
import TaskUpload from "@/views/Task/components/TaskUpload.vue";
import TaskDetail from "@/views/Task/components/TaskDetail.vue";
import TaskEditDialog from "@/views/Task/components/TaskEditDialog.vue";
import { task } from "@/utils/cueWords";
import { uploadAttachment } from "@/api/task";
import axios from "axios";

// 搜索表单
const status = ref("全部");
const name = ref("");
const code = ref("");

// 表格数据
const tableData = ref([]);
// 原始数据备份，用于过滤和重置
const originalTableData = ref([]);

// 本地存储键名
const STORAGE_KEY = "task_table_data";

// 初始化时从本地存储加载数据
onMounted(() => {
  const storedData = localStorage.getItem(STORAGE_KEY);
  if (storedData) {
    try {
      const parsedData = JSON.parse(storedData);
      tableData.value = parsedData;
      originalTableData.value = parsedData;
    } catch (e) {
      console.error("Failed to parse stored data:", e);
    }
  }
});

// 监听tableData变化，保存到本地存储
watch(
  tableData,
  (newValue) => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(newValue));
    // 当tableData发生非过滤性质的变化时，同步更新originalTableData
    if (status.value === "全部" && !name.value && !code.value) {
      originalTableData.value = JSON.parse(JSON.stringify(newValue));
    }
  },
  { deep: true }
);

// 查询方法
const handleSearch = () => {
  // 从原始数据中过滤
  tableData.value = originalTableData.value.filter((item) => {
    // 状态过滤（全部状态不过滤）
    const statusMatch =
      status.value === "" ||
      status.value === "全部" ||
      item.status === status.value;

    // 需求名称过滤（模糊匹配）
    const nameMatch =
      !name.value || item.name.toLowerCase().includes(name.value.toLowerCase());

    // 需求编号过滤（模糊匹配）
    const codeMatch =
      !code.value || item.code.toLowerCase().includes(code.value.toLowerCase());

    // 所有条件都满足才返回true
    return statusMatch && nameMatch && codeMatch;
  });

  console.log("查询条件", {
    status: status.value,
    name: name.value,
    code: code.value,
  });
  console.log("过滤后数据条数:", tableData.value.length);
};

// 重置方法
const resetSearch = () => {
  status.value = "全部";
  name.value = "";
  code.value = "";

  // 恢复原始数据
  tableData.value = JSON.parse(JSON.stringify(originalTableData.value));
  console.log("重置搜索，恢复所有数据");
};

// 文件上传相关
const uploadDialogVisible = ref(false);
const uploadLoading = ref(false);
const aiLoading = ref(false);
let loadingInstance = null;

// 打开上传弹窗
const openUploadDialog = () => {
  uploadDialogVisible.value = true;
};

// 添加响应相关的 ref
const aiResponse = ref("");
const showResponse = ref(false);

// 清除响应内容
const clearResponse = () => {
  aiResponse.value = "";
  showResponse.value = false;
};

// 修改处理上传成功的方法 - 使用模拟上传
const handleUploadSuccess = async (file) => {
  uploadLoading.value = true;
  
  // 原来的真实上传代码（已注释，避免OSS费用）
  // const formData = new FormData();
  // formData.append("file", file);
  // uploadAttachment(formData)
  //   .then((response) => {
  //     uploadLoading.value = false;
  //     handleChat(response.data.data, file.name);
  //   })
  //   .catch((error) => {
  //     uploadLoading.value = false;
  //     ElMessage.error("文件上传失败");
  //     console.error("上传失败:", error);
  //   });
  
  // 模拟上传过程，延迟1秒
  setTimeout(() => {
    uploadLoading.value = false;
    
    // 使用模拟的OSS地址
    const mockOssUrl = "https://test-yy.tos-cn-shanghai.volces.com/%E3%80%90%E5%AE%A2%E6%88%B7%E3%80%91%E4%B8%AD%E5%9B%BD%E9%93%81%E5%A1%94_%E9%93%81%E5%A1%94%E8%A7%86%E8%81%94%E5%B9%B3%E5%8F%B0__%E5%B7%A5%E4%BD%9C%E5%8F%B0-%E9%85%8D%E7%BD%AE%E7%AE%A1%E7%90%86-%E7%AE%97%E6%B3%95%E9%85%8D%E7%BD%AE%E4%BC%98%E5%8C%96_%E9%9C%80%E6%B1%82%E8%A7%84%E6%A0%BC%E8%AF%B4%E6%98%8E%E4%B9%A620250409.docx?X-Tos-Algorithm=TOS4-HMAC-SHA256&X-Tos-Credential=AKLTMjdmZDRlZmU4YmQxNDZhZDlhYjkyMmJlYzMwNmFlNjc%2F20250916%2Fcn-shanghai%2Ftos%2Frequest&X-Tos-Expires=3600&X-Tos-Date=20250916T094513Z&X-Tos-Signature=367111f250495f9d59511edd29c150216cdb342dbbe7c858963e2aa12396001a&X-Tos-SignedHeaders=host";
    
    handleChat(mockOssUrl, file.name);
    ElMessage.success("文件上传成功（模拟）");
  }, 1000);
};

// 处理上传取消
const handleUploadCancel = () => {
  console.log("取消上传");
};

const handleChat = async (
  path,
  fileName = "1.7.40__【客户】中国铁塔_铁塔视联平台__告警详情专业版优化_需求规格说明书20250403.docx"
) => {
  console.log(path);

  // 显示加载状态
  aiLoading.value = true;
  showResponse.value = true;
  aiResponse.value = "";

  // 使用 ElLoading.service 创建全屏加载
  loadingInstance = ElLoading.service({
    fullscreen: true,
    text: "正在处理中...",
    background: "rgba(0, 0, 0, 0.8)",
  });

  const messages1 = [
    {
      role: "system",
      content: task,
    },

    {
      role: "user",
      content: `"${path}",
    1. 根据文档标题，找到对应的版本号。
    2. 分析文档，列出这个版本的新增需求。
    3. 匹配最适合的前段开发人员，后端开发人员。
    4. 并根据敏捷开发思想, 梳理认识任务, 评价任务难易度, 并给出预计测试时间。

    返回JSON 格式字符串，格式如下：
    {
      "iterativeVersion": "文档控制记录中最大的版本号",
      "newDemands": [
        {
          "demandName": "需求名称",
          "demandDescription": "需求描述",
          "difficulty": "难易度",
          "expectedTime": "预计开发时间",
          "startTime": "开始时间 yyyy-MM-dd",
          "endTime": "结束时间 yyyy-MM-dd"
        }
      ],
      "frontEndDeveloper": {
        "name": "前端开发人员姓名",
        "expertise": ["擅长领域1", "擅长领域2"],
        "technologyStack": ["技术栈"],
        "level": "级别"
      },
      "backEndDeveloper": {
        "name": "后端开发人员姓名",
        "expertise": ["擅长领域1", "擅长领域2"],
        "technologyStack": ["技术栈"],
        "level": "级别"
      }
    }`,
    },
  ];

  const requestOptions = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: "doubao-seed-1-6-250615",
      stream: true,
      messages: messages1,
    }),
    keepalive: true,
  };

  try {
    const response = await fetch(
      "http://127.0.0.1:18889/chat",
      requestOptions
    );

    if (!response.ok) {
      throw new Error(`HTTP 错误：${response.status}`);
    }

    // 读取响应体为可读流
    const stream = response.body;
    if (!stream) {
      throw new Error("响应体为空");
    }

    // 创建文本解码器（处理 UTF-8 编码）
    const decoder = new TextDecoder("utf-8");
    const reader = stream.getReader();

    let buffer = "";

    // eslint-disable-next-line no-constant-condition
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }

      const chunk = decoder.decode(value, { stream: true });
      buffer += chunk; // 合并到缓冲区
    }

    console.log(buffer);
    processBuffer(buffer);
    console.log("流读取完成，开始处理响应");
    aiLoading.value = false;
    let parsedData;
    try {
      // 尝试提取JSON格式的数据，查找第一个{和最后一个}之间的内容
      const jsonMatch = aiResponse.value.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        parsedData = JSON.parse(jsonMatch[0]);
      } else {
        // 如果没有找到有效的JSON格式，则尝试直接解析
        parsedData = JSON.parse(aiResponse.value);
      }
    } catch (error) {
      console.error("JSON解析失败:", error);
      ElMessage.error("解析AI响应失败，请重试");
      throw new Error("JSON解析失败");
    }
    console.log("解析后的数据:", parsedData);
    addTask(parsedData, fileName);
    ElMessage.success("成功添加需求");
  } catch (error) {
    console.error("获取流数据失败:", error);
    // 可在此处添加重试逻辑
    ElMessage.error("读取响应流失败");
  } finally {
    aiLoading.value = false;
    // 关闭加载遮罩
    if (loadingInstance) {
      loadingInstance.close();
    }
  }
};

function processBuffer(chunk) {
  // 按 \n 分割行，保留最后一个不完整的行（可能以 \r\n 结尾，需兼容）
  const lines = chunk.split("\n");

  lines.forEach((line) => {
    if (line === "" || line == null) return; // 忽略空行（事件结束符）

    // 处理不同格式的数据
    if (line.startsWith("data:")) {
      let content = "";

      // 处理 data:data: 格式
      if (line.startsWith("data:data:")) {
        const data = line.split("data:data:");
        if (data.length > 1 && data[1] !== "[DONE]") {
          content = data[1];
        }
      }
      // 处理 data: 格式
      else {
        const data = line.substring(5); // 去掉 "data:" 前缀
        if (data && data !== "[DONE]") {
          content = data;
        }
      }

      if (content) {
        try {
          const parsed = JSON.parse(content);
          if (parsed.choices && parsed.choices[0]?.delta?.content) {
            aiResponse.value += parsed.choices[0].delta.content;
          }
        } catch (error) {
          console.log("解析失败=====>");
          console.log(lines);
          console.log(content);
          console.log("解析失败<=====");
          console.error("解析失败:", error);
        }
      }
    }
  });
}

function addTask(parsedData, fileName) {
  console.log("添加的需求:", parsedData); // 确保每个需求都有开发人员相关字段
  if (parsedData && parsedData.newDemands) {
    parsedData.newDemands.forEach((demand) => {
      // 初始化任务级别的开发人员字段
      if (!demand.frontEndDeveloper) {
        demand.frontEndDeveloper = "";
        demand.frontEndDeveloperInfo = { name: "", expertise: [] };
      }
      if (!demand.backEndDeveloper) {
        demand.backEndDeveloper = "";
        demand.backEndDeveloperInfo = { name: "", expertise: [] };
      }
    });
  }

  // 生成需求编号
  const code = `XQ${new Date().getFullYear()}${String(
    tableData.value.length + 1
  ).padStart(3, "0")}`;

  // 创建新的需求记录
  const newTask = {
    code: code,
    name: fileName, // 使用上传文件名作为需求名称
    status: "已分配",
    createTime: new Date().toISOString().split("T")[0],
    extend: parsedData, // 将整个解析后的数据放入 extend 字段
    description: parsedData?.newDemands?.[0]?.demandDescription || "无描述",
    owner: parsedData
      ? `${parsedData.frontEndDeveloper?.name || ""} / ${
          parsedData.backEndDeveloper?.name || ""
        }`
      : "",
  };
  // 添加到表格
  tableData.value.push(newTask);
}

// 编辑相关
const editDialogVisible = ref(false);
const editForm = ref({
  code: "",
  name: "",
  status: "",
  extend: {
    iterativeVersion: "",
    frontEndDeveloper: {
      name: "",
      expertise: [],
    },
    backEndDeveloper: {
      name: "",
      expertise: [],
    },
    newDemands: [],
  },
});

// 添加日期格式化和处理空格的辅助函数
const formatDateRemoveSpaces = (dateString) => {
  if (!dateString) return "";
  return dateString.replace(/\s+/g, ""); // 移除所有空格
};

// 编辑方法
const handleEdit = (row) => {
  // 深拷贝数据，避免直接修改原数据
  editForm.value = JSON.parse(JSON.stringify(row));

  // 为每个需求添加timeRange并处理预计时间
  if (editForm.value.extend && editForm.value.extend.newDemands) {
    editForm.value.extend.newDemands.forEach((demand) => {
      // 处理时间范围，并移除日期中的空格
      if (demand.startTime && demand.endTime) {
        // 确保移除日期字符串中的空格
        demand.startTime = formatDateRemoveSpaces(demand.startTime);
        demand.endTime = formatDateRemoveSpaces(demand.endTime);
        demand.timeRange = [demand.startTime, demand.endTime];
      } else {
        demand.timeRange = [];
      }

      // 处理预计时间格式 - 将"X天"格式转换为数字
      if (demand.expectedTime) {
        if (typeof demand.expectedTime === "string") {
          // 如果是"8天"这种格式，提取数字部分
          const match = demand.expectedTime.match(/^(\d+(\.\d+)?)天?$/);
          if (match) {
            demand.expectedTime = parseFloat(match[1]);
          } else {
            // 尝试直接解析为数字
            const numValue = parseFloat(demand.expectedTime);
            if (!isNaN(numValue)) {
              demand.expectedTime = numValue;
            }
          }
        }
      } else {
        // 默认为1天
        demand.expectedTime = 1;
      }
    });
  }

  editDialogVisible.value = true;
};

// 保存编辑
const saveEdit = (updatedTask) => {
  // 处理所有日期格式，去除空格
  if (updatedTask.extend && updatedTask.extend.newDemands) {
    updatedTask.extend.newDemands.forEach((demand) => {
      if (demand.startTime)
        demand.startTime = formatDateRemoveSpaces(demand.startTime);
      if (demand.endTime)
        demand.endTime = formatDateRemoveSpaces(demand.endTime);
      // 从timeRange同步更新日期
      if (demand.timeRange && demand.timeRange.length === 2) {
        demand.startTime = formatDateRemoveSpaces(demand.timeRange[0]);
        demand.endTime = formatDateRemoveSpaces(demand.timeRange[1]);
      }
    });
  }

  // 找到要编辑的数据索引
  const index = tableData.value.findIndex(
    (item) => item.code === updatedTask.code
  );
  if (index !== -1) {
    // 更新数据
    tableData.value[index] = JSON.parse(JSON.stringify(updatedTask));
    // 同步更新原始数据
    const originalIndex = originalTableData.value.findIndex(
      (item) => item.code === updatedTask.code
    );
    if (originalIndex !== -1) {
      originalTableData.value[originalIndex] = JSON.parse(
        JSON.stringify(updatedTask)
      );
    }
    ElMessage.success("编辑成功");
  } else {
    ElMessage.error("编辑失败：未找到对应数据");
  }
};

// 删除方法
const handleDelete = (row) => {
  // 找到要删除的数据索引
  const index = tableData.value.findIndex((item) => item.code === row.code);
  if (index !== -1) {
    // 删除数据
    tableData.value.splice(index, 1);
    // 同步更新原始数据
    const originalIndex = originalTableData.value.findIndex(
      (item) => item.code === row.code
    );
    if (originalIndex !== -1) {
      originalTableData.value.splice(originalIndex, 1);
    }
    ElMessage.success("删除成功");
  } else {
    ElMessage.error("删除失败：未找到对应数据");
  }
};

// 表格选择相关
const multipleSelection = ref([]);
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
  console.log("当前选中的行:", multipleSelection.value);
};

// 批量操作方法
const handleBatchAction = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  // 创建加载实例
  const loadingInstance = ElLoading.service({
    fullscreen: true,
    text: "正在推送到禅道...",
    background: "rgba(0, 0, 0, 0.7)",
  });

  try {
    let successCount = 0;
    let failedCount = 0;
    const totalTasks = [];
    const invalidTasks = [];

    // 收集所有需要处理的任务，并验证开发人员是否已分配
    multipleSelection.value.forEach((item) => {
      if (
        item.extend &&
        item.extend.newDemands &&
        item.extend.newDemands.length > 0
      ) {
        item.extend.newDemands.forEach((demand) => {
          // 获取任务的开发人员
          const frontEndDev = demand.frontEndDeveloper || "";
          const backEndDev = demand.backEndDeveloper || "";

          // 检查是否至少分配了一个开发人员
          if (!frontEndDev && !backEndDev) {
            invalidTasks.push(`${demand.demandName || "未命名任务"}`);
            return;
          }

          // 确定分配给谁（优先前端，如果没有前端则选后端）
          const assignedTo = frontEndDev || backEndDev;

          totalTasks.push({
            demand,
            taskName: `${demand.demandName || "未命名任务"}`,
            assignedTo,
            taskItem: item,
          });
        });
      }
    });

    // 如果有无效任务，提示并终止操作
    if (invalidTasks.length > 0) {
      loadingInstance.close();
      ElMessage.error(
        `以下任务未分配开发人员，请先分配：${invalidTasks.join(", ")}`
      );
      return;
    }

    console.log("准备推送的任务:", totalTasks);

    // 转换开发人员名称为禅道用户名
    const getZentaoUsername = (developerName) => {
      // 如果开发人员名称为空，返回空数组，不要默认赋值
      if (!developerName) return [];

      const nameMapping = {
        王文权: "wangwenquan",
        慈兆彤: "cizhaotong",
        杨宽: "yangkuan",
        张瑞: "zhangrui",
        易瑶: "yiyao",
        胡恩德: "huende",
        刘政铁: "liuzhengtie",
      };
      return [nameMapping[developerName] || ""]; // 如果找不到映射，返回空字符串
    };

    // 使用 Promise.all 并行处理所有请求
    const results = await Promise.allSettled(
      totalTasks.map(async (task) => {
        try {
          // 处理预计时间，将天转换为小时（1天=8小时）
          let estimate = "8"; // 默认8小时
          console.log(task);
          if (task.demand.expectedTime) {
            // 判断是否包含"天"字
            if (String(task.demand.expectedTime).includes("天")) {
              // 提取数字部分
              const days = parseFloat(
                String(task.demand.expectedTime).replace(/[^0-9.]/g, "")
              );
              if (!isNaN(days)) {
                // 天数乘以8转换为小时
                estimate = String(Math.round(days * 8));
              }
            } else {
              // 如果没有包含"天"，尝试直接提取数字
              const hours = parseFloat(
                String(task.demand.expectedTime).replace(/[^0-9.]/g, "")
              );
              if (!isNaN(hours)) {
                estimate = String(Math.round(hours) * 8);
              }
            }
          }

          // 获取开发人员的禅道用户名
          const assignedToArray = getZentaoUsername(task.assignedTo);

          // 如果没有分配开发人员，跳过此任务
          if (!assignedToArray.length || !assignedToArray[0]) {
            console.warn(`任务 ${task.taskName} 没有有效的开发人员，跳过推送`);
            return {
              success: false,
              task: task.taskName,
              error: "没有有效的开发人员",
            };
          }

          // 构建请求参数
          const requestData = {
            module: "101",
            story: "4174",
            stageId: "1391", // 项目ID
            name: task.taskName, // 任务名称
            desc: task.demand.demandDescription || "",
            assignedTo: assignedToArray, // 分配给谁
            type: "devel", // 类型
            estimate: estimate, // 估计工时(小时)
            estStarted:
              formatDateRemoveSpaces(task.demand.startTime) ||
              new Date().toISOString().split("T")[0], // 开始时间，去除空格
            deadline: formatDateRemoveSpaces(task.demand.endTime) || "", // 结束时间，去除空格
          };

          console.log("推送任务参数:", requestData);

          // 调用接口
          const response = await axios.post(
            "http://127.0.0.1:18889/zentao/executions/create",
            requestData
          );

          console.log("推送成功:", task.taskName, response.data);

          // 更新该需求的状态为已推送
          if (task.taskItem) {
            task.taskItem.status = "已推送";
          }

          return { success: true, task: task.taskName };
        } catch (error) {
          console.error("推送失败:", task.taskName, error);
          return { success: false, task: task.taskName, error };
        }
      })
    );

    // 统计成功和失败数量
    results.forEach((result) => {
      if (result.status === "fulfilled" && result.value.success) {
        successCount++;
      } else {
        failedCount++;
      }
    });

    // 显示结果
    if (successCount > 0 && failedCount === 0) {
      ElMessage.success(`成功推送 ${successCount} 个任务到禅道`);
    } else if (successCount > 0 && failedCount > 0) {
      ElMessage.warning(
        `推送结果: ${successCount} 个成功, ${failedCount} 个失败`
      );
    } else {
      ElMessage.error(`推送失败: ${failedCount} 个任务未能成功推送`);
    }
  } catch (error) {
    console.error("批量操作异常:", error);
    ElMessage.error("推送过程中发生错误");
  } finally {
    // 关闭加载显示
    loadingInstance.close();
  }
};

// 格式化日期为yyyy-MM-dd
const formatDate = (dateString) => {
  if (!dateString) return "";

  try {
    const date = new Date(dateString);
    if (isNaN(date.getTime())) return dateString; // 如果无法解析为日期，返回原字符串

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
  } catch (error) {
    console.error("日期格式化错误:", error);
    return dateString;
  }
};
</script>

<style scoped lang="scss">
.task-container {
  padding: 16px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);

  .form-card {
    margin-bottom: 16px;
    background-color: #fff;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-weight: bold;
      font-size: 16px;
    }

    .search-row {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      gap: 16px;

      .search-item {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        .label {
          margin-right: 8px;
          color: #606266;
          font-size: 14px;
        }

        .input-width {
          width: 200px;
        }
      }

      .buttons {
        margin-left: auto;
        display: flex;
        gap: 8px;
      }
    }
  }

  .task-list-card {
    .left-actions {
      display: flex;
      align-items: center;
    }

    .right-actions {
      display: flex;
      gap: 8px;
    }

    .add-task-btn,
    .action-btn {
      display: flex;
      align-items: center;
      gap: 4px;
    }

    .divider {
      height: 1px;
      background-color: #e0e0e0;
      margin: 0 0 16px 0;
      width: 100%;
    }

    .task-table {
      margin-top: 8px;
      border-radius: 4px;
      overflow: hidden;
    }
  }

  .response-card {
    margin-top: 16px;

    .response-content {
      padding: 16px;
      background-color: #f8f8f8;
      border-radius: 4px;
      min-height: 100px;
      max-height: 500px;
      overflow-y: auto;
      white-space: pre-wrap;
      line-height: 1.6;
      font-size: 14px;
      word-break: break-all;
    }
  }

  :deep(.el-table) {
    --el-table-header-bg-color: #f5f7fa;
    --el-table-row-hover-bg-color: #f0f7ff;

    th {
      font-weight: 600;
    }
  }

  :deep(.el-table__expanded-cell) {
    padding: 20px !important;
    background-color: #f8f8f8;
  }
}

// 动画效果
.list-enter-active,
.list-leave-active {
  transition: all 0.3s ease;
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateY(30px);
}
</style>
